﻿Imports System
Imports System.Web
Imports System.Net
Imports System.IO
Imports Mollie.iDEAL
Imports NEvoWeb.Modules.NB_Store
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Collections.Specialized
Namespace FortyFingers.DNN.Modules.NBStore.Mollie
    Public Class IdealGateway
        Inherits GatewayInterface

        Private Const GatewaySettingsName As String = "FortyFingers.MollieIdeal.gateway"
        Private Const GatewaySettingsNameOld As String = "40Fingers.MollieIdeal.gateway"

        Public Overrides Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String) As String
            Dim strHTML As String = ""
            Dim objSCtrl As New SettingsController
            Dim objSInfo As NB_Store_SettingsInfo

            UpdateLog(String.Format("Mollie-GetButtonHtml: OrderID={0}", OrderID))

            ''get the gateway settings from the NB_Store settings table
            'objSInfo = objSCtrl.GetSetting(PortalID, GatewaySettingsName, Lang)
            'If objSInfo Is Nothing Then
            '    UpdateLog(String.Format("Mollie-GetButtonHtml: Fetching old setting name"))

            '    objSInfo = objSCtrl.GetSetting(PortalID, GatewaySettingsNameOld, Lang)
            'End If

            'Move the xml format settingn into the a hashtable so we can use it easily.
            Dim setParams As Hashtable = GatewayParams(PortalID)

            strHTML = String.Format("<input type=""submit""><img src=""{0}""></input>", setParams("ButtonImageURL"))
            Dim blnTestMode As Boolean

            If Not Boolean.TryParse(setParams("MollieTestmode"), blnTestMode) Then
                blnTestMode = True
            End If

            'Build Html to display the payment button.
            Dim strOptionsHTML As String = ""
            Try
                For Each oBank As Bank In New IdealBanks(setParams("MolliePartnerID"), blnTestMode).Banks
                    strOptionsHTML &= String.Format("<option value=""{0}"">{1}</option>", oBank.Id, oBank.Name)
                Next

                strHTML = SharedFunctions.GetStoreSettingText(PortalID, "FortyFingers.MollieIdeal.template", SharedFunctions.GetCurrentCulture())

                If String.IsNullOrEmpty(strHTML) Then strHTML = ButtonHTML

                strHTML = strHTML.Replace("[BANKSELECTOROPTIONSHTML]", strOptionsHTML) _
                                    .Replace("[BUTTONIMAGEURL]", setParams("ButtonImageURL"))

            Catch ex As Exception

                UpdateLog(String.Format("Mollie-GetButtonHtml: Exception occurred:{0}", ex.Message))

            End Try

            UpdateLog(String.Format("Mollie-GetButtonHtml: Html length={0}, {1}", strHTML.Length, strHTML.Substring(0, 100)))

            Return strHTML
        End Function

        Public Overrides Sub AutoResponse(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest)

            Try
                Dim objSCtrl As New SettingsController
                Dim objOCtrl As New OrderController
                Dim objPCtrl As New ProductController
                Dim objOInfo As NB_Store_OrdersInfo

                'Mollie gives us the transaction Id in the request.
                Dim transactionId As String = Request("transaction_id")
                Dim strCartId As String = Request("cartid")
                Dim intOrderId As Integer = Null.NullInteger

                Integer.TryParse(Request("orderid"), intOrderId)
                If intOrderId <= 0 Then
                    Integer.TryParse(Request("ordid"), intOrderId)
                End If

                Dim setParams As Hashtable = GatewayParams(PortalID)

                'Check the payment
                Dim oIdealCheck As New IdealCheck(setParams("MolliePartnerID"), Boolean.Parse(setParams("MollieTestmode")), transactionId)

                ' ------------------------------------------------------------------------
                'Log response data so we can tell if the auto response has worked.
                UpdateLog("AUTO = TransactionID:" & transactionId & " Payed: " & oIdealCheck.Payed.ToString & " Errormessage:" & oIdealCheck.ErrorMessage)

                'we need to get the nbstore order with the transactionid

                'clear cart parameters, this is not strictly needed but does help tidy things up.
                Dim objCCtrl As New CartController
                Dim objCInfo As NB_Store_CartInfo = objCCtrl.GetCart(strCartId)
                If Not objCInfo Is Nothing Then
                    objCInfo.BankTransID = -1
                    objCInfo.BankHtmlRedirect = ""
                    objCCtrl.UpdateObjCart(objCInfo)
                End If
                ' ------------------------------------------------------------------------
                ' This section updates the order.
                objOInfo = objOCtrl.GetOrder(intOrderId)
                If Not objOInfo Is Nothing Then
                    'check that the order is valid. (Not yet been processed)
                    If Not objOInfo.OrderIsPlaced Then
                        If oIdealCheck.Payed Then
                            ' check if order has already been processed
                            If Not objOInfo.OrderIsPlaced Then
                                'remove qty in trans
                                objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                                'set order status to Payed
                                objOInfo.OrderStatusID = 40
                                Dim UsrID As Integer = objOInfo.UserID
                                If UsrID = -1 Then UsrID = 0
                                objOInfo.OrderNumber = Format(PortalID, "00") & "-" & UsrID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                                objOInfo.OrderIsPlaced = True
                                objOCtrl.UpdateObjOrder(objOInfo)
                                'Send email confirmation
                                'SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentOK.email", "")
                                SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentOK.email")
                            End If
                        Else 'Payment failed
                            'check if order has already been cancelled
                            If Not objOInfo.OrderStatusID = 30 Then
                                'remove qty in trans
                                objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                                'set order status to cancelled
                                objOInfo.OrderStatusID = 30
                                objOCtrl.UpdateObjOrder(objOInfo)
                            End If
                        End If
                    End If
                End If
            Catch ex As Exception
                DotNetNuke.Services.Exceptions.LogException(ex) 'something went wrong, lets log the error...
                SendEmailToAdministrator(PortalID, "AutoReturn ERROR", ex.ToString)
            End Try

        End Sub

        Public Overrides Function GetCompletedHtml(ByVal PortalID As Integer, ByVal UserID As Integer, ByVal Request As System.Web.HttpRequest) As String
            Return GatewayParams(PortalID)("PaymentCompletedHTML")
        End Function

        Private Function GatewayParams(ByVal PortalId As Integer) As Hashtable
            Dim objSInfo As NB_Store_SettingsInfo
            Dim objSCtrl As New SettingsController

            objSInfo = objSCtrl.GetSetting(PortalId, GatewaySettingsName, GetCurrentLangCode())
            If objSInfo Is Nothing Then
                UpdateLog(String.Format("Mollie-GatewayParams: Fetching old setting name"))
                objSInfo = objSCtrl.GetSetting(PortalId, GatewaySettingsNameOld, GetCurrentLangCode())
            End If

            'Get the gateway settings from the store setting Database
            If Not objSInfo Is Nothing Then
                'Parse the gateway setttings into a Hashtable for easy access.
                Return createSettingsTable(objSInfo.SettingValue)
            Else
                Return New Hashtable
            End If

        End Function

        Public Overrides Function GetBankClick(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest) As Boolean
            'test if button has been clicked
            If Not Request.Form.Item("mollieidealgatewaybankselectorbutton") Is Nothing Then
                Return True
            Else
                Return False
            End If
        End Function

        Public Overrides Sub SetBankRemotePost(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal Request As System.Web.HttpRequest)
            Dim RPost As RemotePost ' RemotePost class from NB_Store, this generates the re-direct html required.
            'test if DummyPay button has been clicked
            If GetBankClick(PortalID, Request) Then
                Dim setParams As Hashtable = GatewayParams(PortalID)

                '-------------------------------------------------
                'Get the basic required data from the settings.
                ' with the exception of the ReturnNotifyURL, these parameters are usually always required, by a payment provider
                ' Obviously they may have different names depending on the provider.
                Dim partnerId As String = setParams("MolliePartnerID")
                Dim testmode As String = setParams("MollieTestmode")
                Dim returnUrl As String = setParams("ReturnUrl")
                Dim reportUrl As String = setParams("ReportUrl")
                '-------------------------------------------------

                '-------------------------------------------------
                ' Get any other needed parameters.
                ' These requirement of these parameters may differ, depending on the payment provider.
                Dim cartDescription As String = setParams("CartDescription")
                Dim bank As String = Request.Form("mollieidealgatewaybankselectordropdown")

                'Get the cart data from the database.
                Dim objCInfo As NB_Store_CartInfo = CurrentCart.GetCurrentCart(PortalID)

                '-------------------------------------------------
                'Get the order we want to pay for.
                Dim objOCtrl As New OrderController
                Dim oInfo As NB_Store_OrdersInfo = objOCtrl.GetOrder(OrderID)
                If Not oInfo Is Nothing Then

                    If Not String.IsNullOrEmpty(cartDescription) Then
                        cartDescription = cartDescription.Replace("[ORDERID]", OrderID.ToString())
                    End If

                    Dim strCartId As String = objCInfo.CartID

                    returnUrl = returnUrl.Replace("[ORDERID]", oInfo.OrderID.ToString)
                    reportUrl = reportUrl.Replace("[ORDERID]", oInfo.OrderID.ToString)

                    returnUrl = returnUrl.Replace("[CARTID]", strCartId)
                    reportUrl = reportUrl.Replace("[CARTID]", strCartId)

                    'Initiate the Mollie payment
                    Dim oIdealFetch As New IdealFetch( _
                                            partnerId _
                                            , testmode _
                                            , cartDescription _
                                            , reportUrl _
                                            , returnUrl _
                                            , bank _
                                            , oInfo.Total)

                    'oIdealFetch.Custom = "40FINGERS Mollie iDEAL Gatewayprovider for NB_Store - www.40fingers.net"

                    'Only continue if a transaction was initiated
                    If oIdealFetch.Error Then
                        UpdateLog(oInfo.UserID, String.Format("IDealFetch error. ErrorMessage={0}", oIdealFetch.ErrorMessage))
                        Throw New Exception(oIdealFetch.ErrorMessage)
                    End If

                    'update stock transaction in progress
                    Dim objPCtrl As New ProductController
                    objPCtrl.UpdateModelQtyTrans(oInfo.OrderID)

                    'set order status to redirect to bank
                    oInfo.OrderStatusID = 20
                    objOCtrl.UpdateObjOrder(oInfo)

                    'get the gateway processing image we're going to display while connecting to the payment provider.
                    Dim gatewayImg As String = GetStoreSetting(PortalID, "gateway.loadimage", "None")
                    'Now assign the URL we've received from Mollie to the RemotePost class, ready to build the re-direct html.
                    RPost = New RemotePost
                    RPost.Url = oIdealFetch.Url

                    '-------------------------------------------------
                    'We are now going to save the re-direct html into the cart data on the database.
                    ' This is because the actual re-direct is done by the checkout module, when it loads.

                    'Build and assign the re-direct html to the cart.
                    Dim postHtml As String = String.Format(BankRedirectHTML, oIdealFetch.Url) 'RPost.GetPostHtml(gatewayImg)

                    'some banks need a GET i.s.o. POST
                    'postHtml = postHtml.Replace("method=""post""", "method=""get""")
                    objCInfo.BankHtmlRedirect = postHtml

                    'Save this data on the cart.
                    CurrentCart.Save(objCInfo)

                    '-------------------------------------------------
                    'Do a log statement of the url created, so we have a trace of what data has been passed.
                    UpdateLog("Mollie iDEAL URL = " & oIdealFetch.Url)
                End If
            End If
        End Sub

        Public Function createSettingsTable(ByVal SettingsParams As String) As Hashtable
            Return ParseGateway(SettingsParams)
        End Function

        Private Const BankRedirectHTML As String = "<html><head></head><body onload=""document.location = '{0}';""></body></html>"

        Private Const ButtonHTML As String = "<script type='text/javascript'>" _
& "jQuery(document).ready(function() {" _
& "  jQuery('#mollieidealgatewaybankselector').hide();" _
& "  jQuery('#mollieidealgatewaybutton').click(function() { jQuery('#mollieidealgatewaybankselector').toggle(250); });" _
& "  jQuery('#mollieidealgatewaybankselectordropdown').change( function() {" _
& "    var sel = jQuery('#mollieidealgatewaybankselectordropdown option:selected:first');" _
& "    if(sel.text() != '') {" _
& "        jQuery('#mollieidealgatewaybankselectorbutton').removeAttr('disabled');" _
& "      }" _
& "  });" _
& "});" _
& "</script>" _
& "" _
& "<div style='float: left;'>" _
& "  <img alt='' id='mollieidealgatewaybutton' src='[BUTTONIMAGEURL]' /><br />" _
& "  <div id='mollieidealgatewaybankselector'>" _
& "    Selecteer uw bank:<br />" _
& "    <select id='mollieidealgatewaybankselectordropdown' name='mollieidealgatewaybankselectordropdown'>" _
& "      <option></option>" _
& "      [BANKSELECTOROPTIONSHTML]" _
& "    </select><br />" _
& "    <input type='submit' id='mollieidealgatewaybankselectorbutton' name='mollieidealgatewaybankselectorbutton' value='Start betaling' disabled='disabled' />" _
& "  </div>" _
& "</div>"

    End Class
End Namespace